﻿using AspectCore.Extensions.DependencyInjection;
using System.Reflection;

namespace HystrixDemo.Ext
{
    public static class InterceptorHelper
    {
        public static void RegsiterServices(this WebApplicationBuilder builder, Assembly assembly)
        {

            foreach (Type type in assembly.GetTypes())
            {
                //    Console.WriteLine("Type:" + type.Name);
                var hasAttributer = type.GetMethods().Any(m => m.GetCustomAttribute(typeof(CustomInterceptorAttribute)) != null);
                if (hasAttributer)
                {
                    // assembly.GetType(type.Name.Remove(0, 1));
                    var name = type.Name.Remove(0, 1);
                    var newType = assembly.GetType(type.FullName.Replace(type.Name, name));
                    if (newType != null)
                    {
                        builder.Services.AddSingleton(type, newType);
                    }

                    //  services.AddSingleton(type, type);
                }


            }


            builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());

        }

    }
}
